/*
 * TODO
 */
package com.xtrip.util.parse.xml;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;

import com.xtrip.adm.model.City;

/**
 * @project xtrip
 * @author shiming.yao
 * @time 2013-5-27
 */
public class CtripParser {

	private static Element getRootElement(Document doc){
		return doc.getRootElement();
	}
	
	public static List<Map<String,String>> parse(Document doc,String itemName,List<String> nodeNames){
		List<Map<String,String>> result = new ArrayList<Map<String,String>>();
		Element rootElement = getRootElement(doc);
		List<Element> items = rootElement.elements(itemName);
		System.out.println(items.size());	
		for(int i=0;i<10;i++){
			Element item = items.get(i);
			Map<String,String> map = new HashMap<String,String>();
			for(int j=0;j<nodeNames.size();j++){
				String nodeName = nodeNames.get(j);
				Node node = item.element(nodeName);
				String value = node.getStringValue();
				map.put(nodeName, value);
			}
			result.add(map);
		}
		return result;
	}
	//CTRIP城市
	public static List<City> parseCtripCity(Document doc,String itemName){
		List<City> result = new ArrayList<City>();
		Element rootElement = getRootElement(doc);
		List<Element> items = rootElement.elements(itemName);
		System.out.println(items.size());
		for(int i=0;i<items.size();i++){
			Element item = items.get(i);
			City c = new City();
			Iterator<Element> it = item.elementIterator();
			while(it.hasNext()){
				Element e = it.next();
				if(e.getName().equals("City")){
					c.setCtripCid(e.getStringValue());
				} else if(e.getName().equals("CityName")){
					String name = e.getStringValue();
					if(name.length()>2 && name.substring(name.length()-1).equals("市")){
						name = name.substring(0, name.length()-1);
					}
					c.setName(name);
				} else if(e.getName().equals("Province")){
					c.setProId(e.getStringValue());
				} 
			}
			result.add(c);
		}
		return result;
	}
}
